const common = require('../../utils/common')
const { SELLTYPELIST, RETURNGOODSTYPELIST } = require('../../utils/constant')
const { getAfterSaleApply, applyAftersale, getRefundAmount } = require('../../services/order')
const { uploadFile } = require('../../services/upload')
Page({
  data: {
    orderData: {
    },
    goodsList: [], // 商品列表
    orderId: '',
    reasonIndex: '',
    reasonList: [],
    checkedAll: true,
    sellTypeList: SELLTYPELIST,
    returnGoodsTypeList: RETURNGOODSTYPELIST,
    actionList: ["拍照", "从手机相册选择"],
    formData: {
      afterType: 0, // 1仅退款 0退货退款
      alterDetail: [],
      linkHrefList: [], // 售后图片集合
      orderId: '',
      reason: '',
      returnAmount: '', //退款金额
      type: 1, //退货类型 1全部退货 0部分退货
      applyRemark: '', //备注
    },
    enable: false,
    maxUpload: 6,
  },
  onLoad: function ({ id }) {
    if (!id) return
    this.setData({
      orderId: id
    })
    this.getSellDetail(id)
  },
  updateFormData: function (payload) {
    this.setData({
      formData: { ...this.data.formData, ...payload }
    }, this.canSubmit)
  },
  getSellDetail: function (orderId) {
    getAfterSaleApply({ orderId }).then((res) => {
      const goodsList = res.data.detail && res.data.detail.map(v => {
        return { ...v, checked: true }
      })
      this.setData({
        orderData: res.data,
        goodsList,
        reasonList: res.data.reasonList,
      }, this.updateAlterDetail)
    }).catch((err) => {
      common.log(err)
    })
  },
  onSelectorChange: function (e) {
    const reasonIndex = e.detail.value
    this.updateFormData({
      reason: this.data.reasonList[reasonIndex]
    })
    this.setData({
      reasonIndex,
    })
  },
  sellTypeChange: function (e) {
    const { value } = e.currentTarget.dataset
    this.updateFormData({ afterType: value })
  },
  returnGoodsTypeChange: function (e) {
    const { value } = e.currentTarget.dataset
    this.updateFormData({ type: value })
    if (value == 1) {
      this.toggleCheckedAll(true)
    }
  },
  toggleChecked: function (e) {
    if (this.data.formData.type == 1) return
    const { index } = e.currentTarget.dataset
    const goodsList = this.data.goodsList
    const current = goodsList[index]
    current.checked = !current.checked
    goodsList.splice(index, 1, current)
    this.setData({
      goodsList,
    }, this.updateAlterDetail)
  },
  toggleCheckedAll: function (flag) {
    const newList = this.data.goodsList.map((v) => {
      return { ...v, checked: flag }
    })
    this.setData({
      goodsList: newList
    }, this.updateAlterDetail)
  },

  canSubmit: function () {
    let enable = false
    const { reason, alterDetail } = this.data.formData
    if (reason && alterDetail && alterDetail.length > 0) {
      enable = true
    } else {
      enable = false
    }
    this.setData({
      enable
    })
    return enable
  },
  updateAlterDetail: function () {
    const checkedGoods = this.data.goodsList.filter(v => v.checked) || []
    const alterDetail = checkedGoods.map(v => ({ afterAmount: v.refundAmount, orderDetailId: v.id })) || []
    this.updateFormData({ alterDetail })
    // 退款金额计算
    getRefundAmount({ alterDetail }).then((res) => {
      this.updateFormData({ returnAmount: res.data })
    }).catch((err) => {
      common.log(err)
    })
  },
  //上传照片
  selectPhoto: function () {
    if (this.data.formData.linkHrefList.length >= this.data.maxUpload) {
      common.showToast("最多上传六张图片")
      return
    }
    common.showActionSheet(this.data.actionList, (res) => {
      if (res.tapIndex == 0) {
        this.chooseImage('camera');
      } else if (res.tapIndex == 1) {
        this.chooseImage('album');
      }
    });
  },
  chooseImage: function (type) {
    wx.chooseImage({
      count: this.data.maxUpload,
      sourceType: [type],
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        const allUpload = tempFilePaths.map((path) => {
          return uploadFile(path)
        })
        Promise.all(allUpload).then((res) => {
          const linkHrefList = [...this.data.formData.linkHrefList, ...res]
          this.updateFormData({ linkHrefList })
        }).catch(err => {
          common.showToast('上传失败')
        })
      },
      fail: res => {
        var canceled = res.errMsg.indexOf("cancel") != -1;
        if (!canceled) {
          common.showToast(res.errMsg);
        }
      }
    });
  },
  removeImage: function (e) {
    const { index } = e.currentTarget.dataset
    const linkHrefList = this.data.formData.linkHrefList
    linkHrefList.splice(index, 1)
    this.updateFormData({ linkHrefList })
  },
  noteChange: function (e) {
    const applyRemark = e.detail.value
    this.updateFormData({ applyRemark })
  },
  onConfirm: function () {
    if (!this.data.enable) return
    const { reason, alterDetail } = this.data.formData
    if (!reason) {
      common.showToast("请选择退货原因")
      return
    }
    if (!alterDetail || alterDetail.length <= 0) {
      common.showToast("请选择退货商品")
      return
    }
    const data = { ...this.data.formData, orderId: this.data.orderId }
    applyAftersale(data).then((res) => {
      wx.navigateTo({ url: `/pages/sell-service-result/index?type=${this.data.formData.afterType}&payload=${JSON.stringify(res.data)}` })
    }).catch(err => {
      common.log(err)
    })
  },
})
